package com.example.juc.demobase;


//创建资源类  定义属性和操作方法


import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Share {
    //初始值
    private int number = 0;

    public synchronized void add() throws InterruptedException {

        if (number != 0) {
            this.wait();
        }

        if (number == 0)
            number++;


        System.out.println(Thread.currentThread().getName() + "number:" + number);
        this.notifyAll();
    }

    public synchronized void sub() throws InterruptedException {

        while (number != 1){
            if (number != 1) {
                this.wait();
            }
        }


        if (number == 1)
            number--;

        System.out.println(Thread.currentThread().getName() + "number:" + number);
        this.notifyAll();
    }
}



class Share2 {

    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();
    //初始值
    private int number = 0;

    public synchronized void add() {
        try{
            while (number != 0){
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "number:" + number);
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
        lock.unlock();
        }

    }
    public synchronized void sub(){
        try{
            while (number != 1){
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "number:" + number);
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }
    }

}


public class ThreadDemo01 {

    public static void main(String[] args) throws InterruptedException {

        Share share = new Share();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {

                for (int i = 0; i < 10; i++) {
                    try {
                        share.add();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }, "t1");


        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {

                for (int i = 0; i < 10; i++) {
                    try {
                        share.sub();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }, "t2");
        t1.start();
        t2.start();

    }
}



